package com.yidiandao.business.ui.widget.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.View;
import android.view.ViewGroup;

import com.yidiandao.business.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 指定搜索内容-Layout
 * <p>
 * Created by ChenTao(chentao7v@gmail.com) on 2017/4/12 0012 9:43
 */
public class SearchFlowLayout extends ViewGroup {

    public static final String TAG = "SearchFlowLayout";

    /**
     * 默认水平间隔, 0
     */
    private static final float DEFAULT_HORIZONTAL_SPACING = 0;

    /**
     * 默认垂直间隔, 10dp.
     */
    private static final float DEFAULT_VERTICAL_SPACING = 25;

    /**
     * 水平间隔.
     */
    private int mHorizontalSpacing;

    /**
     * 垂直间隔.
     */
    private int mVerticalSpacing;

    private List<View> mRemoveDividerViews;

    private SparseIntArray mLinesExtraDistance;

    private OnSearchTagClickListener mListener;

    public SearchFlowLayout(Context context) {
        this(context, null);
    }

    public SearchFlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SearchFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttrs(context, attrs);
        initVariables();
    }

    private void initVariables() {
        mRemoveDividerViews = new ArrayList<>();
        mLinesExtraDistance = new SparseIntArray();
    }

    private void initAttrs(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SearchFlowLayout);
        try {
            mHorizontalSpacing = typedArray.getDimensionPixelOffset(
                    R.styleable.SearchFlowLayout_horizontalSpace, dp2px((int) DEFAULT_HORIZONTAL_SPACING));
            mVerticalSpacing = typedArray.getDimensionPixelOffset(
                    R.styleable.SearchFlowLayout_verticalSpace, dp2px((int) DEFAULT_VERTICAL_SPACING));
        } finally {
            typedArray.recycle();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        mLinesExtraDistance.clear();
        mRemoveDividerViews.clear();

        // 通过计算 对child进行测量后，设置自己的宽度与高度
        int widthSize = resolveSize(0, widthMeasureSpec);

        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();
        int paddingRight = getPaddingRight();
        int paddingBottom = getPaddingBottom();

        int childLeft = paddingLeft;
        int childTop = paddingTop;

        int lineHeight = 0;
        View childView;

        int lineCount = 0;

        int lastChildLift = 0;

        for (int i = 0, childCount = getChildCount(); i < childCount; i++) {

            childView = getChildAt(i);
            // 测量Child，获取child的宽高信息
            measureChild(childView, widthMeasureSpec, heightMeasureSpec);
            // 测量之后可以获取到Child的宽度与高度
            int childWidth = childView.getMeasuredWidth();
            int childHeight = childView.getMeasuredHeight();

            lineHeight = Math.max(childHeight, lineHeight);

            if (childLeft + childWidth + paddingRight > widthSize) {

                // 记录上一行的多余的左间距
                mLinesExtraDistance.put(lineCount, (widthSize - lastChildLift) / 2);
                lineCount++;

                // 换行,需要加上竖直方向间距
                childLeft = paddingLeft + childWidth;
                childTop += lineHeight + mVerticalSpacing;
                lineHeight = childHeight;

                // 记下需要remove的 Divider
                View lastView = getChildAt(i - 1);
                // 上一行的最后一个是Divider,移除
                if (lastView instanceof SearchTagDivider) {
                    mRemoveDividerViews.add(lastView);
                }

                // 如果当前行的第一个是Divider,移除
                if (childView instanceof SearchTagDivider) {
                    mRemoveDividerViews.add(lastView);
                }

                lastChildLift = childLeft;

            } else {
                // 未换行,需要加上水平方向间距
                childLeft += childWidth + mHorizontalSpacing;

                lastChildLift = childLeft;
            }
        }

        // 计算随后一行的 左间距
        mLinesExtraDistance.put(lineCount, (widthSize - lastChildLift) / 2);

        // 移除每一行的最后一个 Divider
        for (int i = 0; i < mRemoveDividerViews.size(); i++) {
            removeView(mRemoveDividerViews.get(i));
        }

        Log.w(TAG, "extra : " + mLinesExtraDistance.toString());

        // 高度要包含最后一行的高度
        int heightSize = childTop + lineHeight + paddingBottom;

        // 测量自己的宽度与高度
        setMeasuredDimension(widthSize, resolveSize(heightSize, heightMeasureSpec));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int widthSize = r - l;
        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();
        int paddingRight = getPaddingRight();

        int lineCount = 0;
        int childLeft = paddingLeft + mLinesExtraDistance.get(0);

        int childTop = paddingTop;

        int lineHeight = 0;
        View childView;

        for (int i = 0, childCount = getChildCount(); i < childCount; i++) {

            childView = getChildAt(i);

            int childWidth = childView.getMeasuredWidth();
            int childHeight = childView.getMeasuredHeight();

            lineHeight = Math.max(childHeight, lineHeight);

            if (childLeft + childWidth + paddingRight > widthSize) {
                // 换行
                lineCount++;
                childLeft = paddingLeft + mLinesExtraDistance.get(lineCount);

                // 距离右边距离要加上右间距
                childTop += lineHeight + mVerticalSpacing;
                lineHeight = childHeight;
            }
            // 对child进行layout
            childView.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
            // 距离左边距离要加上间距
            childLeft += childWidth + mHorizontalSpacing;
        }
    }

    public void setData(final List<String> data) {
        removeAllViews();

        if (data == null) {
            return;
        }

        int size = data.size();
        if (size == 0) {
            return;
        }

        for (int i = 0; i < size; i++) {
            SearchTagView tagView = new SearchTagView(getContext());
            tagView.setText(data.get(i));
            addView(tagView);

            final int finalI = i;
            tagView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        mListener.onSearchTagClick(data.get(finalI), finalI);
                    }
                }
            });

            if (i != (size - 1)) {
                SearchTagDivider divider = new SearchTagDivider(getContext());
                addView(divider);
            }
        }
    }

    public int dp2px(int dp) {
        // px = dp * (dpi / 160)
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        int dpi = metrics.densityDpi;

        return (int) (dp * (dpi / 160f) + 0.5f);
    }

    public void setOnSearchTagClickListener(OnSearchTagClickListener listener) {
        mListener = listener;
    }

    public interface OnSearchTagClickListener {
        void onSearchTagClick(String text, int position);
    }
}
